package org.yc;

import java.io.*;
import java.util.*;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

class Student {
    private String name, gender, major, className;
    private int studentID, age;
    private Map<String, Integer> courseScores; // 课程及成绩
    private Map<String, Integer> courseCredits; // 课程及学分

    public Student(String name, String gender, int studentID, int age, String major, String className) {
        this.name = name;
        this.gender = gender;
        this.studentID = studentID;
        this.age = age;
        this.major = major;
        this.className = className;
        this.courseScores = new HashMap<>();
        this.courseCredits = new HashMap<>();
    }

    // 添加课程成绩
    public void addCourse(String course, int score, int credits) {
        this.courseScores.put(course, score);
        this.courseCredits.put(course, credits);
    }

    // 计算GPA
    public double calculateGPA() {
        double totalScore = 0;
        double totalCredits = 0;
        for (String course : courseScores.keySet()) {
            int score = courseScores.get(course);
            int credits = courseCredits.get(course);
            totalScore += score * credits;
            totalCredits += credits;
        }
        return totalCredits > 0 ? totalScore / totalCredits : 0;
    }

    // GPA 转换为字母成绩
    public String getLetterGrade() {
        double gpa = calculateGPA();
        if (gpa >= 90) {
            return "A";
        } else if (gpa >= 86) {
            return "A-";
        } else if (gpa >= 83) {
            return "B+";
        } else if (gpa >= 80) {
            return "B";
        } else if (gpa >= 76) {
            return "B-";
        } else if (gpa >= 73) {
            return "C+";
        } else if (gpa >= 70) {
            return "C";
        } else if (gpa >= 66) {
            return "C-";
        } else if (gpa >= 63) {
            return "D+";
        } else if (gpa >= 60) {
            return "D";
        } else {
            return "F";
        }
    }

    // 输出学生信息，包括字母成绩
    public void printStudentInfo() {
        System.out.println("姓名: " + name);
        System.out.println("性别: " + gender);
        System.out.println("学号: " + studentID);
        System.out.println("年龄: " + age);
        System.out.println("专业: " + major);
        System.out.println("班级: " + className);
        System.out.println("课程和成绩:");
        for (String course : courseScores.keySet()) {
            System.out.println(course + ": " + courseScores.get(course) + " (学分: " + courseCredits.get(course) + ")");
        }
        System.out.println("GPA: " + calculateGPA() + " (" + getLetterGrade() + ")");
    }
    
    public int getStudentID() {
        return studentID;
    }

    public String getName() {
        return name;
    }

    public Map<String, Integer> getCourseScores() {
        return courseScores;
    }

    public Map<String, Integer> getCourseCredits() {
        return courseCredits;
    }
}

class StudentManager {
    private Map<Integer, Student> studentDatabase;

    public StudentManager() {
        studentDatabase = new HashMap<>();
    }

    // 添加学生
    public void addStudent(Student student) {
        studentDatabase.put(student.getStudentID(), student);
    }

    // 根据学号获取学生
    public Student getStudentByID(int studentID) {
        return studentDatabase.get(studentID);
    }

    // 显示所有学生信息
    public void displayAllStudents() {
        for (Student student : studentDatabase.values()) {
            student.printStudentInfo();
            System.out.println("---------------------------");
        }
    }

    // 从Excel导入学生数据
    public void importStudentsFromExcel(String importFilePath) throws Exception {
        FileInputStream file = new FileInputStream(new File(importFilePath));
        Workbook workbook = new XSSFWorkbook(file);
        Sheet sheet = workbook.getSheetAt(0);
        Iterator<Row> rowIterator = sheet.iterator();

        // Skip header row
        rowIterator.next();

        Map<Integer, Student> tempDatabase = new HashMap<>(); // 临时保存学生信息，避免重复

        while (rowIterator.hasNext()) {
            Row row = rowIterator.next();
            String name = row.getCell(0).getStringCellValue();
            String gender = row.getCell(1).getStringCellValue();
            int studentID = (int) row.getCell(2).getNumericCellValue();
            int age = (int) row.getCell(3).getNumericCellValue();
            String major = row.getCell(4).getStringCellValue();
            String className = row.getCell(5).getStringCellValue();
            String course = row.getCell(6).getStringCellValue();
            int score = (int) row.getCell(7).getNumericCellValue();
            int credits = (int) row.getCell(8).getNumericCellValue();

            // 检查是否已经存在该学生
            Student student = tempDatabase.get(studentID);
            if (student == null) {
                student = new Student(name, gender, studentID, age, major, className);
                tempDatabase.put(studentID, student);
            }

            // 添加课程成绩
            student.addCourse(course, score, credits);
        }

        // 将所有学生添加到主数据库中
        for (Student student : tempDatabase.values()) {
            studentDatabase.put(student.getStudentID(), student);
        }

        workbook.close();
        file.close();
    }

    public void exportStudentScoresToFile(String filePath) throws IOException {
        // 使用UTF-8编码
        try (BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(filePath), "UTF-8"))) {
            for (Student student : studentDatabase.values()) {
                // 输出姓名、GPA 和字母成绩
                writer.write("姓名: " + student.getName() + " - GPA: " + student.calculateGPA() + " (" + student.getLetterGrade() + ")");
                writer.newLine();
                // 输出课程成绩
                for (Map.Entry<String, Integer> entry : student.getCourseScores().entrySet()) {
                    writer.write(entry.getKey() + ": " + entry.getValue() + " (学分: " + student.getCourseCredits().get(entry.getKey()) + ")");
                    writer.newLine();
                }
                writer.newLine();
            }
        }
    }
}

public class StudentCreditManagementSystem {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        StudentManager studentManager = new StudentManager();

        // 设置静态的Excel文件路径和输出文件路径
        String importFilePath = "D:/student_data.xlsx"; // Excel文件的静态路径
        String exportFilePath = "D:/student_data.txt"; // TXT文件的静态路径

        while (true) {
            System.out.println("欢迎使用学生学分管理系统");
            System.out.println("1. 显示所有学生");
            System.out.println("2. 添加学生");
            System.out.println("3. 按学号查看学生信息");
            System.out.println("4. 从Excel导入学生数据");
            System.out.println("5. 导出成绩到文件");
            System.out.println("6. 退出");
            System.out.print("请选择操作: ");
            
            // 检查输入是否为整数
            if (!scanner.hasNextInt()) {
                System.out.println("无效输入，请输入一个数字。");
                scanner.next(); // 清除错误输入
                continue;
            }

            int choice = scanner.nextInt();
            scanner.nextLine(); // 消耗换行符

            if (choice == 1) {
                studentManager.displayAllStudents();
            } else if (choice == 2) {
                System.out.print("请输入学生姓名: ");
                String name = scanner.nextLine();
                System.out.print("请输入性别: ");
                String gender = scanner.nextLine();
                System.out.print("请输入学号: ");
                int studentID = scanner.nextInt();
                scanner.nextLine(); // 消耗换行符
                System.out.print("请输入年龄: ");
                int age = scanner.nextInt();
                scanner.nextLine(); // 消耗换行符
                System.out.print("请输入专业: ");
                String major = scanner.nextLine();
                System.out.print("请输入班级: ");
                String className = scanner.nextLine();

                Student student = new Student(name, gender, studentID, age, major, className);
                studentManager.addStudent(student);

                System.out.print("请输入课程数: ");
                int numCourses = scanner.nextInt();
                scanner.nextLine(); // 消耗换行符

                for (int i = 0; i < numCourses; i++) {
                    System.out.print("请输入课程名: ");
                    String course = scanner.nextLine();
                    System.out.print("请输入成绩: ");
                    int score = scanner.nextInt();
                    System.out.print("请输入学分: ");
                    int credits = scanner.nextInt();
                    scanner.nextLine(); // 消耗换行符

                    student.addCourse(course, score, credits);
                }
            } else if (choice == 3) {
                System.out.print("请输入学号: ");
                int studentID = scanner.nextInt();
                Student student = studentManager.getStudentByID(studentID);
                if (student != null) {
                    student.printStudentInfo();
                } else {
                    System.out.println("未找到该学号的学生。");
                }
            } else if (choice == 4) {
                try {
                    studentManager.importStudentsFromExcel(importFilePath);
                    System.out.println("学生数据导入成功！");
                } catch (Exception e) {
                    System.out.println("导入数据时发生错误: " + e.getMessage());
                }
            } else if (choice == 5) {
                try {
                    studentManager.exportStudentScoresToFile(exportFilePath);
                    System.out.println("成绩已成功导出到文件。");
                } catch (IOException e) {
                    System.out.println("导出成绩时发生错误: " + e.getMessage());
                }
            } else if (choice == 6) {
                System.out.println("感谢使用学生学分管理系统！");
                break;
            } else {
                System.out.println("无效操作，请重新选择！");
            }
        }

        scanner.close();
    }
}
